/**
 * 版权所有(C)，中国银联股份有限公司，2002-2013，所有权利保留。
 * 
 * 项目名：	simple-web
 * 文件名：	FunctionInfoAction.java
 * 模块说明：	
 * 修改历史：
 * 2013-11-7 - Administrator - 创建。
 */
package com.aeky.simple.action.functionInfo;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.aeky.simple.action.BaseAction;
import com.aeky.simple.cache.CacheManager;
import com.aeky.simple.cache.CacheType;
import com.aeky.simple.cache.DataCache;
import com.aeky.simple.entity.FunctionInfo;
import com.aeky.simple.enums.EnableStatusEnum;
import com.aeky.simple.enums.FunctionTypeEnum;
import com.aeky.simple.service.FunctionInfoService;
import com.aeky.simple.util.DateUtil;
import com.aeky.simple.vo.page.Pager;
import com.aeky.simple.vo.tree.TreeNode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.opensymphony.xwork2.Action;

/**
 * 资源权限管理Action
 * 
 * @author wanghui
 * 
 */
public class FunctionInfoAction extends BaseAction {

    private static final long serialVersionUID = 990967797947491042L;

    @Autowired
    private FunctionInfoService functionInfoService;

    /**
     * 初始化资源权限管理页面
     * 
     * @return
     * @throws Exception
     */
    public String initFunctionInfo() throws Exception {
        return Action.SUCCESS;
    }

    /**
     * 初始化资源信息新增页面
     * 
     * @return
     * @throws Exception
     */
    public String initAddFunctionInfo() throws Exception {
        return "initAdd";
    }

    /**
     * 分页查询资源信息
     * 
     * @return
     * @throws Exception
     */
    public String listFunctionInfo() throws Exception {
        final String sysCode = request.getParameter("sysCode");
        final String funcCode = request.getParameter("funcCode");
        final String funcName = request.getParameter("funcName");
        final String funcType = request.getParameter("funcType");
        Pager<FunctionInfo> pager = new Pager<FunctionInfo>(request.getParameter("page"),
                        request.getParameter("rows"));
        final Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("sysCode", sysCode);
        paramMap.put("funcCode", funcCode);
        paramMap.put("funcName", funcName);
        paramMap.put("funcType", funcType);
        try {
            pager = functionInfoService.queryFunctionInfoList(pager, paramMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ajaxResult = this.getJsonFromObject(changeToMapPager(pager));
        return AJAX_RESULT;
    }

    /**
     * 子类可重写此方法添加额外的map属性
     * 
     * @param t
     * @param map
     */
    public <T> void addOtherMapValue(T t, Map<String, Object> map) {
        FunctionInfo fi = (FunctionInfo) t;
        map.put("sysName", DataCache.getInstance().getSystemInfoBySysCode(fi.getSysCode())
                        .getSysName());
        map.put("funcTypeName", FunctionTypeEnum.getEnumNameByValue(fi.getFuncType()));
        map.put("funcStatusName", EnableStatusEnum.getEnumNameByValue(fi.getFuncStatus()));
        map.put("recordCrtTime", DateUtil.formatDateDefaultDisplay(fi.getRecordCrtTime()));
        map.put("recordUpdTime", DateUtil.formatDateDefaultDisplay(fi.getRecordUpdTime()));
    }

    public String addFunctionInfo() throws Exception {
        final String jsonString = request.getParameter("funcInfo");
        Gson gson = new Gson();
        Type type = new TypeToken<FunctionInfo>() {
        }.getType();
        final FunctionInfo funcInfo = gson.fromJson(jsonString, type);
        funcInfo.setRecordCrtOperLoginName(this.getLoginUserName());
        funcInfo.setRecordUpdOperLoginName(this.getLoginUserName());
        try {
            functionInfoService.addFunctionInfo(funcInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        CacheManager.refreshSystemFunctionInfosCache();
        ajaxResult = buildJSONResponse("success", "资源信息添加成功！");
        return AJAX_RESULT;
    }

    public String initEditFunctionInfo() throws Exception {
        final String sysCode = request.getParameter("sysCode");
        final String funcCode = request.getParameter("funcCode");
        final Integer version = Integer.valueOf(request.getParameter("version"));
        FunctionInfo fi = null;
        try {
            fi = functionInfoService.queryFunctionInfoByPKAndVersion(sysCode, funcCode, version);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (fi == null) {
            ajaxResult = buildJSONResponse("fail", "数据版本有变，将刷新页面！");
        } else {
            ajaxResult = buildJSONResponse("success",
                            this.getJsonFromObject(converterObjectToMap(fi)));
        }
        return AJAX_RESULT;
    }

    public String editFunctionInfo() throws Exception {
        final String jsonString = request.getParameter("funcInfo");
        Gson gson = new Gson();
        Type type = new TypeToken<FunctionInfo>() {
        }.getType();
        final FunctionInfo funcInfo = gson.fromJson(jsonString, type);
        funcInfo.setRecordUpdOperLoginName(this.getLoginUserName());
        try {
            functionInfoService.updateFunctionInfo(funcInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        CacheManager.refreshSystemFunctionInfosCache();
        ajaxResult = buildJSONResponse("success", "操作成功");
        return AJAX_RESULT;
    }

    public String getFuncInfoComboxValue() throws Exception {
        final String sysCode = request.getParameter("sysCode");
        final String funcType = request.getParameter("funcType");

        if ("0".equals(funcType)) {
            List<TreeNode> tnList = new ArrayList<TreeNode>();
            TreeNode root = new TreeNode();
            root.setId(sysCode);
            DataCache dataCache = CacheManager.getCache(CacheType.AUTH_DATA_CACHE);
            root.setText(dataCache.getSysInfoCache().get(sysCode).getSysName());
            tnList.add(root);
            ajaxResult = this.getJsonFromObject(tnList);
            return AJAX_RESULT;
        }

        List<FunctionInfo> list = null;
        try {
            list = functionInfoService.queryFuncInfoComboxValue(sysCode, funcType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (list != null && !list.isEmpty()) {
            Map<String, FunctionInfo> tempCache = new HashMap<String, FunctionInfo>();
            // 模块-菜单map
            Map<String, List<FunctionInfo>> sysModelMap = new LinkedHashMap<String, List<FunctionInfo>>();
            if (list != null && !list.isEmpty()) {
                for (FunctionInfo fi : list) {
                    final String funcCodeTemp = fi.getFuncCode();// 资源编号
                    final String funcTypeTemp = fi.getFuncType();// 资源类型
                    tempCache.put(funcCodeTemp, fi);
                    if ("0".equals(funcTypeTemp)) {
                        if (!sysModelMap.containsKey(funcTypeTemp)) {
                            sysModelMap.put(funcCodeTemp, new ArrayList<FunctionInfo>());
                        }
                    }
                }
                for (Map.Entry<String, List<FunctionInfo>> map : sysModelMap.entrySet()) {
                    final String funcCodeTemp = map.getKey();
                    final List<FunctionInfo> fiList = map.getValue();
                    for (FunctionInfo fi : list) {
                        if (fi.getParentFuncCode().equals(funcCodeTemp)) {
                            fiList.add(fi);
                        }
                    }
                }
            }
            List<TreeNode> tnList = new ArrayList<TreeNode>();
            TreeNode root = new TreeNode();
            root.setId(sysCode);
            DataCache dataCache = CacheManager.getCache(CacheType.AUTH_DATA_CACHE);
            root.setText(dataCache.getSysInfoCache().get(sysCode).getSysName());
            root.setState("open");
            List<TreeNode> list0 = new ArrayList<TreeNode>();
            for (Map.Entry<String, List<FunctionInfo>> map : sysModelMap.entrySet()) {
                TreeNode funcType0 = new TreeNode();
                final String funcCode = map.getKey();
                final FunctionInfo fi = tempCache.get(funcCode);
                funcType0.setId(fi.getFuncCode());
                funcType0.setText(fi.getFuncName());
                if ("2".equals(funcType)) {
                    final List<FunctionInfo> fiList = map.getValue();
                    List<TreeNode> l = new ArrayList<TreeNode>();
                    for (FunctionInfo functionInfo : fiList) {
                        TreeNode funcType1 = new TreeNode();
                        funcType1.setId(functionInfo.getFuncCode());
                        funcType1.setText(functionInfo.getFuncName());
                        funcType1.setState("open");
                        l.add(funcType1);
                    }
                    funcType0.setChildren(l);
                }
                list0.add(funcType0);
            }
            root.setChildren(list0);
            tnList.add(root);
            ajaxResult = this.getJsonFromObject(tnList);
            System.out.println(ajaxResult);
            return AJAX_RESULT;
        } else {
            ajaxResult = "[]";
            return AJAX_RESULT;
        }
    }

    /**
     * 删除资源信息
     * 
     * @return
     * @throws Exception
     */
    public String deleteFunctionInfo() throws Exception {
        final String sysCode = request.getParameter("sysCode");
        final String funcCode = request.getParameter("funcCode");
        final String version = request.getParameter("version");
        try {
            functionInfoService.deleteFunctionInfo(sysCode, funcCode, Integer.valueOf(version));
        } catch (Exception e) {
            e.printStackTrace();
        }
        CacheManager.refreshSystemFunctionInfosCache();
        ajaxResult = buildJSONResponse("success", "操作成功");
        return AJAX_RESULT;
    }

}
